package com.mdinfo.gw.door.driver;

import com.mdinfo.base.common.bean.CommonResult;
import com.mdinfo.base.common.bean.Ref;
import com.mdinfo.gw.door.bean.DoorAccess;
import com.mdinfo.gw.door.driver.aopu.AopuClient;
import com.mdinfo.gw.door.driver.aopu.AopuReadOpration;
import com.mdinfo.gw.door.driver.utils.ByteUtil;
import com.mdinfo.gw.door.mapper.DoorAccessMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2018/1/31.
 */
@Service
public class DoorDriver {

    @Resource
    private DoorAccessMapper accessMapper;

    private Map<Integer,AopuClient> clientMap = new ConcurrentHashMap<>();
    private Logger logger = LoggerFactory.getLogger(DoorDriver.class);

    @PostConstruct
    public void init(){
        EventLoopGroup group = new NioEventLoopGroup();
        //获取所有可用的门禁
        List<DoorAccess> accessList = accessMapper.listAllUsable();
        for(DoorAccess doorAccess : accessList){

            Integer accessId = doorAccess.getId();
            String host = doorAccess.getHost();
            Integer port = doorAccess.getPort();
            AopuReadOpration readOpration = new AopuReadOpration(accessId);
            AopuClient aopuClient = new AopuClient(host,port,group,readOpration);
            clientMap.put(accessId,aopuClient);
        }

    }

    public CommonResult<Void> openDoor(Integer accessId,Integer doorId){
        logger.info("开门,门禁<"+accessId+">--门<"+doorId+">");
        Integer[] ints = {0x02,0xa0,0x2c,0xff,doorId,0x00,0x00};
        byte[] bytes = ByteUtil.getBytes(ints);
        AopuClient aopuClient = clientMap.get(accessId);
        if(aopuClient==null){
            return Ref.error("找不到对应的门禁控制器");
        }
        if(!aopuClient.isConn()){
            return Ref.error("连接中断,发送失败");
        }
        aopuClient.sendData(bytes);
        return Ref.ok();
    }

    public CommonResult<Void> closeDoor(Integer accessId,Integer doorId){
        logger.info("关门,门禁<"+accessId+">--门<"+doorId+">");
        Integer[] ints = {0x02,0xa0,0x2e,0xff,doorId,0x00,0x00};
        byte[] bytes = ByteUtil.getBytes(ints);
        AopuClient aopuClient = clientMap.get(accessId);
        if(aopuClient==null){
            return Ref.error("找不到对应的门禁控制器");
        }
        if(!aopuClient.isConn()){
            return Ref.error("连接中断,发送失败");
        }
        aopuClient.sendData(bytes);
        return Ref.ok();
    }
}
